<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:edit']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plainf
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:user:remove']"
        >退团
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="50" align="center" :selectable="checkSelectable"/>
      <!--      <el-table-column type="expand" align="center">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="用户名称">
                    <span>{{ props.row.userName }}</span>
                  </el-form-item>
                  <el-form-item label="用户昵称">
                    <span>{{ props.row.nickName }}</span>
                  </el-form-item>
                  <el-form-item label="联系方式">
                    <span>{{ props.row.phonenumber }}</span>
                  </el-form-item>
                  <el-form-item label="邮箱">
                    <span>{{ props.row.email }}</span>
                  </el-form-item>
                  <el-form-item label="社团">
                    <span>{{ props.row.dept.deptName }}</span>
                  </el-form-item>
                  <el-form-item label="店铺地址">
                    <span>{{ props.row.address }}</span>
                  </el-form-item>
                  <el-form-item label="商品描述">
                    <span>{{ props.row.desc }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>-->
      <el-table-column label="用户编号" width="80" align="center" key="userId" prop="userId" v-if="columns[0].visible"/>
      <el-table-column label="用户名称" align="center" key="userName" prop="userName" v-if="columns[1].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" v-if="columns[2].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="社团" align="center" key="deptName" prop="dept.deptName" v-if="columns[3].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" v-if="columns[4].visible"
                       width="120"/>
      <el-table-column label="在团状态" key="deptStatus" align="center" prop="deptStatus" :formatter="statusFormat"
                       v-if="columns[5].visible" width="100"/>
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.deptStatus=='1'"
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handleUpdate('agree',scope.row)"
            v-hasPermi="['system:user:edit']"
          >同意
          </el-button>
          <el-button
            v-if="scope.row.deptStatus=='1'"
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="handleUpdate('refuse',scope.row)"
            v-hasPermi="['system:user:edit']"
          >拒绝
          </el-button>
          <el-button
            :disabled="scope.row.userId === 1?true:false"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']"
          >退团
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加 -->
    <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="0px">
        <el-row>
          <el-col :span="24">
<!--            <div style="padding-bottom: 15px;">请输入添加人的用户名/手机号/邮箱</div>
            <el-form-item prop="userName" style="margin-bottom:0px">
              <el-input v-model="form.userName" placeholder="请输入用户名/手机号/邮箱"/>
            </el-form-item>-->
            <div style="padding-bottom: 15px;">请选择要添加的用户</div>
            <el-select style="width: 100%" v-model="form.userName" filterable placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <!--            <el-input v-model="form.userName" placeholder="请输入用户名/手机号/邮箱"/>-->
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" size="small">取 消</el-button>
        <el-button size="small" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title2" width="30%" :visible.sync="open2" append-to-body center>
      <el-form ref="form2" :model="form2" :rules="rules" size="medium" label-width="12px">
        <el-form-item label=" " prop="remark">
          <el-input v-model="form2.remark" type="textarea" placeholder="请输入原因" :maxlength="500" show-word-limit
                    :autosize="{minRows: 5, maxRows: 20}" :style="{width: '100%'}"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="btnClick=='拒绝'" @click="submitFormJJ" type="danger" round>提 交</el-button>
        <el-button v-if="btnClick=='退团'" @click="submitFormTT" type="danger" round>提 交</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog @close="onClose" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport"/>
          是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listUserDept, listUser, exportUser, importTemplate, changeDept, delUserDept, getDept} from "@/api/system/user";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {mapGetters} from 'vuex'
import {addMessage} from "@/api/system/message";

export default {
  name: "Person",
  components: {Treeselect},
  data() {
    return {
      options: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      userDepts: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      userList2: [],
      // 弹出层标题
      title: "",
      title2: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      // 社团名称
      deptName: undefined,
      // 日期范围
      dateRange: [],
      // 用户社团状态
      userDeptOptions: [],
      // 表单参数
      form: {},
      form2: {},
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 列信息
      columns: [
        {key: 0, label: `用户编号`, visible: true},
        {key: 1, label: `用户名称`, visible: true},
        {key: 2, label: `用户昵称`, visible: true},
        {key: 3, label: `社团`, visible: true},
        {key: 4, label: `手机号码`, visible: true},
        {key: 5, label: `在团状态`, visible: true},
        {key: 6, label: `入团时间`, visible: true}
      ],
      // 表单校验
      rules: {
        userName: [
          {required: true, message: "添加用户不能为空", trigger: "blur"}
        ],
        remark: [{required: true, message: '原因不能为空', trigger: 'blur'}],
      },
      userInfo: '',
      btnClick: '',
    };
  },
  watch: {
    // 根据名称筛选社团树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  computed: {
    deptId() {
      return this.$route.params && this.$route.params.deptId;
    },
    deptNameValue() {
      return this.$route.params && this.$route.params.deptName;
    },
    ...mapGetters([
      'user',
    ])
  },
  created() {
    this.getList();
    this.getDicts("sys_user_dept").then(response => {
      this.userDeptOptions = response.data;
    });
  },
  methods: {
    checkSelectable(row) {
      return !row.admin
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      this.queryParams.deptId = this.deptId
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.userDeptOptions, row.deptStatus);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: []
      };
      this.options=[]
      this.userList2=[]
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.names = selection.map(item => item.userName);
      this.userDepts = selection.map(item => item.dept.deptName);
      console.log(this.userDepts)
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 添加按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
      let queryParams = {
        status: '0',
      }
      listUser(queryParams).then(response => {
          this.userList2 = response.rows
          this.userList2=this.userList2.filter(item=>{
            return !item.deptId
          });
          this.userList2.map(item=>{
            let aa={
              value:item.userName,
              label:item.userName
            }
            this.options.push(aa)
          })
        }
      );
    },
    /** 审核按钮操作 */
    handleUpdate(btn, row) {
      if (btn == 'agree') {
        this.$confirm('是否确认同意"' + row.userName + '"的用户入团?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return changeDept(JSON.stringify(row), 'agree');
        }).then(() => {
          this.msgSuccess("同意入团成功");
          this.getList();
          let message = {
            fromId: this.user.userId,
            fromName: this.user.userName,
            toId: row.userId,
            toName: row.userName,
            messageTitle: this.info.deptTitle,
            payload: JSON.stringify({remark: this.info.deptInfo}),
            messageContent: this.infoMsg('deptSqAgree', row.dept.deptName),
            type: '0',
          }
          addMessage(message)
        })
      } else if (btn == 'refuse') {
        this.form2 = {}
        this.resetForm('form2')
        this.userInfo = row
        this.open2 = true
        this.title2 = "拒绝原因"
        this.btnClick = '拒绝'
        /* this.$confirm('是否确认拒绝"' + row.userName + '"的用户入团?', "警告", {
           confirmButtonText: "确定",
           cancelButtonText: "取消",
           type: "warning"
         }).then(function () {
           return changeDept(JSON.stringify(row), 'refuse');
         }).then(() => {
           this.getList();
           this.msgSuccess("拒绝入团成功");
           let message = {
             fromId: this.user.userId,
             fromName: this.user.userName,
             toId: row.userId,
             toName: row.userName,
             messageTitle: '社团申请拒绝',
             messageContent: '【' + row.dept.deptName + '】社团负责人拒绝了您的申请，请注意查看！'
           }
           addMessage(message)
         })*/
      }
    },
    //关闭
    onClose() {
      this.userInfo = ''
    },
    //拒绝提交
    submitFormJJ() {
      let row = JSON.parse(JSON.stringify(this.userInfo))
      this.$refs['form2'].validate(valid => {
        if (valid) {
          changeDept(JSON.stringify(row), 'refuse').then(res => {
            this.msgSuccess("拒绝入团成功");
            this.open2 = false
            this.getList()
            let message = {
              fromId: this.user.userId,
              fromName: this.user.userName,
              toId: row.userId,
              toName: row.userName,
              messageTitle: this.info.deptTitle,
              payload: JSON.stringify(this.form2),
              messageContent: this.infoMsg('deptSqRefuse', row.dept.deptName),
              type: '0',
            }
            addMessage(message)
          });
        }
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let data = {userName: this.form.userName}
          listUserDept(data).then(response => {
            let res = response.data
            changeDept(JSON.stringify(res), 'add', JSON.stringify(this.deptId)).then(response => {
              this.msgSuccess("添加成功");
              this.open = false;
              this.getList();
              let message = {
                fromId: this.user.userId,
                fromName: this.user.userName,
                toId: res.userId,
                toName: res.userName,
                messageTitle: this.info.deptTitleAdd,
                payload: JSON.stringify({remark: this.info.deptInfo}),
                messageContent: this.infoMsg('deptAdd', this.deptNameValue),
                type: '0',
              }
              addMessage(message)
            });
          });
        }
      });
    },
    /** 退团按钮操作 */
    handleDelete(row) {
      this.form2 = {}
      this.resetForm('form2')
      this.userInfo = row
      this.open2 = true
      this.title2 = "退团原因"
      this.btnClick = '退团'
      /*console.log(row)
      const userIds = row.userId || this.ids;
      const userNames = row.userName || this.names;
      const userdept = row.dept.deptName || this.userDepts;
      this.$confirm('是否确认退团用户编号为"' + userIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delUserDept(userIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("退团成功");
        if (!row.userId) {
          for (let i = 0; i < userNames.length; i++) {
            let message = {
              fromId: this.user.userId,
              fromName: this.user.userName,
              toId: userIds[i],
              toName: userNames[i],
              messageTitle: '社团清退',
              messageContent: '【' + userdept[i] + '】社团负责人直接将你清退，请注意查看！'
            }
            addMessage(message)
          }
        } else {
          let message = {
            fromId: this.user.userId,
            fromName: this.user.userName,
            toId: row.userId,
            toName: row.userName,
            messageTitle: '社团清退',
            messageContent: '【' + row.dept.deptName + '】社团负责人直接将你清退，请注意查看！'
          }
          addMessage(message)
        }
      })*/
    },
    submitFormTT() {
      let row = JSON.parse(JSON.stringify(this.userInfo))
      const userIds = row.userId || this.ids;
      const userNames = row.userName || this.names;
      const userdept = this.userDepts || row.dept.deptName;
      this.$refs['form2'].validate(valid => {
        if (valid) {
          delUserDept(userIds).then(res => {
            this.msgSuccess("退团成功");
            this.open2 = false
            this.getList();
            if (!row.userId) {
              for (let i = 0; i < userNames.length; i++) {
                let message = {
                  fromId: this.user.userId,
                  fromName: this.user.userName,
                  toId: userIds[i],
                  toName: userNames[i],
                  messageTitle: this.info.deptTitleDel,
                  payload: JSON.stringify(this.form2),
                  messageContent: this.infoMsg('deptDel', userdept[i]),
                  type: '0',
                }
                addMessage(message)
              }
            } else {
              let message = {
                fromId: this.user.userId,
                fromName: this.user.userName,
                toId: row.userId,
                toName: row.userName,
                messageTitle: this.info.deptTitleDel,
                payload: JSON.stringify(this.form2),
                messageContent: this.infoMsg('deptDel', row.dept.deptName),
                type: '0',
              }
              addMessage(message)
            }
          })
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportUser(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>

<style scoped>
/deep/ .el-pagination__editor.el-input .el-input__inner {
  height: 28px;
  line-height: 36px;
}

/deep/ .el-input--medium .el-input__inner {
  height: 40px;
  line-height: 40px;
}

/deep/ .el-dialog__body {
  padding: 20px;
}

/*/deep/ .el-form-item__content {
  margin-left: 0 !important;
}*/
</style>
